#!/usr/bin/env python3.10
# -*- encoding: utf-8 -*-
"""
@File    :   schema.py
@Time    :   2024/01/29 10:44:54
@Author  :   windstarry 
@Version :   1.0
"""
# here put the import lib

from pydantic import validator
from datetime import datetime
from typing import List, Optional, Type

from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group
from ninja import Field
from ninja_schema import ModelSchema, Schema, model_validator
from ninja_extra import status
from ninja_extra.exceptions import APIException

# 获取用户模型
UserModel = get_user_model()

# Group显示字段
class GroupSchema(ModelSchema):
    class Config:
        model = Group
        include = ("name",)
        
# 用户登录请求字段
class LoginSchema(Schema):
    username: str = Field(..., description="用户名")
    password: str = Field(..., description="密码")

# 用户创建请求字段
class CreateUserSchema(ModelSchema):
    class Config:
        model = UserModel
        include = (
            "username",
            "email",
            "password",
        )

    # 验证username是否存在
    @model_validator("username")
    def unique_name(cls, value_data):
        """
        检查用户名是否唯一

        Args:
            cls: 类名
            value_data: 待检查的用户名数据

        Returns:
            str: 如果用户名唯一，则返回该用户名数据

        Raises:
            APIException: 如果用户名已存在,则抛出API异常

        """
        if UserModel.objects.filter(username__icontains=value_data).exists():
            raise APIException("用户名已存在", code=status.HTTP_400_BAD_REQUEST)
        return value_data

    def create(self) -> Type[UserModel]:
        """
        创建用户并返回创建的用户对象。

        :return: 创建的用户对象
        :rtype: Type[UserModel]
        """
        return UserModel.objects.create_user(**self.dict())


class UserRetrieveSchema(ModelSchema):
    groups: List[GroupSchema]

    class Config:
        model = UserModel
        include = ("id", "username", "email", "status")

       
class UserTokenOutSchema(Schema):
    token: str
    user: UserRetrieveSchema
    token_exp_date: Optional[datetime]
    
    
class EnableDisableUserSchema(Schema):
    user_id: int
    _user = None

    @validator(
        "user_id",
    )
    def validate_user_id(cls, value):
        """
        验证用户Id是否有效

        Args:
            cls: 类的实例
            value: 需要验证的用户Id

        Returns:
            int: 验证通过的用户Id

        Raises:
            ValueError: 如果用户Id无效
        """
        user = UserModel.objects.filter(id=value).first()
        if user:
            cls._user = user
            return value
        raise ValueError("用户Id无效")

    def update(self):
        """
        更新用户状态

        :return: 更新后的用户对象
        """
        self._user.status = not self._user.status
        self._user.save()
        return self._user

    def delete(self):
        _id = self._user.id
        self._user.delete()
        return _id


class EnableDisableUserOutSchema(Schema):
    message: str

